import request from '@/utils/request'

const loadDict = function(dictCode) {
  return new Promise((resolve, reject) => {
    if (dictCode) {
      request({
        url: '/api/craneDictItem/getByDictCode',
        data: { dictCode: dictCode },
        method: 'post'
      }).then(function(res) {
        resolve(converStructure(res))
      })
    } else {
      reject({ code: '500', message: '字典类型不可为空' })
    }
  })
}

const loadDictTable = function(data) {
  return new Promise((resolve, reject) => {
    if (data && data.dictTable && data.dictLabel && data.dictValue) {
      request({
        url: '/api/craneDictItem/getByDictTable',
        data,
        method: 'post'
      }).then(function(res) {
        resolve(converStructure(res))
      })
    } else {
      reject({ code: '500', message: '字典表参数缺失' })
    }
  })
}

const converStructure = function(res) {
  const options = []
  res && res.data && res.data.forEach(element => {
    options.push({
      dictValue: element.itemCode,
      dictLabel: element.itemValue
    })
  })
  return options
}

export {
  loadDict,
  loadDictTable
}
